package com.example.liuyuhan

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import java.io.File

class FirstActivity:AppCompatActivity() {
    private val historyFileName = "history.txt"
    private var calculationJob: Job? = null
    private val primeResults = mutableListOf<Int>()
    private lateinit var tvResult: TextView
    private lateinit var btnCalculate: Button
    private lateinit var btnStop: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        btnCalculate = findViewById(R.id.btnCalculate)
        val etMin: EditText = findViewById(R.id.etMin)
        val etMax: EditText = findViewById(R.id.etMax)
        tvResult = findViewById(R.id.tvResult)
        btnStop = findViewById(R.id.btnStop)

        loadHistory()

        // 设置计算按钮点击事件
        btnCalculate.setOnClickListener {
            val min = etMin.text.toString().toIntOrNull()
            val max = etMax.text.toString().toIntOrNull()

            if (min != null && max != null && min <= max) {
                startPrimeCalculation(min, max)
            } else {
                tvResult.text = "请输入有效的数字区间"
            }
        }

        // 停止计算按钮点击事件
        btnStop.setOnClickListener {
            stopCalculation()
        }
    }

    // 创建菜单项
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    // 处理菜单项点击事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_history -> {
                // 启动历史记录 Activity
                val intent = Intent(this, HistoryActivity::class.java)
                startActivity(intent)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun startPrimeCalculation(min: Int, max: Int) {
        // 停止之前的计算
        stopCalculation()

        tvResult.text = "计算中..."
        primeResults.clear()

        // 启动新线程进行计算
        calculationJob = lifecycleScope.launch(Dispatchers.Default) {
            for (number in min..max) {
                if (!isActive) break  // 如果计算被取消，退出循环
                if (isPrime(number)) {
                    primeResults.add(number)
                    updateResult(primeResults.joinToString(", "))
                }
            }
            saveHistory()  // 保存结果到文件
        }
    }

    private fun stopCalculation() {
        calculationJob?.cancel()  // 取消当前的 Job
        tvResult.text = "计算已停止"
    }

    private suspend fun updateResult(result: String) {
        withContext(Dispatchers.Main) {
            tvResult.text = result
        }
    }

    private fun isPrime(number: Int): Boolean {
        if (number < 2) return false
        for (i in 2..Math.sqrt(number.toDouble()).toInt()) {
            if (number % i == 0) return false
        }
        return true
    }

    private fun saveHistory() {
        val file = File(filesDir, historyFileName)
        file.writeText(primeResults.joinToString(","))
    }

    private fun loadHistory() {
        val file = File(filesDir, historyFileName)
        if (file.exists()) {
            val history = file.readText().split(",").mapNotNull { it.toIntOrNull() }
            primeResults.addAll(history)
            tvResult.text = "历史记录: ${primeResults.joinToString(", ")}"
        }
    }
}

